﻿﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using System.Diagnostics;
using RedBit.UserVoice.OAuth;
using Hammock.Authentication.OAuth;
using Hammock;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Hammock.Web;
using Hammock.Streaming;
using System.IO.IsolatedStorage;
using RedBit.UserVoice.Services;


namespace RedBit.UserVoice
{
    public class UserVoiceAPI
    {
        public static UserVoiceAPI Default = new UserVoiceAPI();

        //TODO: double check performance here and possibly change to seperate file and binary serialization
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        internal static string Key { get; set; }
        internal static string Secret { get; set; }
        internal static string AppName { get; set; }

        private static RequestToken m_accessToken = null;
        public static RequestToken AccessToken 
        {
            get { return m_accessToken; }
            set
            {
                m_accessToken = value;
                if (m_accessToken == null)
                {
                    appSettings.Remove("access_token");
                    appSettings.Remove("access_secret");
                }
                else
                {
                    appSettings["access_token"] = m_accessToken.Key;
                    appSettings["access_secret"] = m_accessToken.Secret;
                }
                appSettings.Save();
                
            }
        }

        private UserVoiceAPI()
        {

        }

        private OAuthCredentials BuildCredentials()
        {
            var credentials = new OAuthCredentials
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = Key,
                ConsumerSecret = Secret,
            };
            return credentials;
        }

        public static void Initalize(string key, string secret, string appName)
        {
            Key = key;
            Secret = secret;
            AppName = appName;
            checkForAccessToken();
        }

        
        private static void checkForAccessToken()
        {
            if (appSettings.Contains("access_token"))
            {
                var rt = new RequestToken
                {
                    Key = appSettings["access_token"].ToString(),
                    Secret = appSettings["access_secret"].ToString()
                };

                AccessToken = rt;
            }
        }
    }
}
